package org.tang.springcloudvv.config;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * <p><em>Created on 2022/10/13 4:29 下午</em></p>
 * 把插件注入到sqlSessionFactory中
 * @author fuzhongtang
 * @since 1.0.1
 */
@Configuration
public class PluginHelper {

    protected static final Logger logger = LoggerFactory.getLogger(PluginHelper.class);

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @PostConstruct
    public void injectPlugin()
    {
        String interceptor = "org.tang.springcloudvv.interceptor.MybatisSqlInterceptor";
        Properties properties = new Properties();

        Interceptor interceptorInstance = build(interceptor);
        interceptorInstance.setProperties(properties);
        sqlSessionFactory.getConfiguration().addInterceptor(interceptorInstance);
    }

    private Interceptor  build(String interceptor)
    {
        try
        {
            Class  clazz = (Class) Resources.classForName(interceptor);
            Interceptor interceptorInstance = (Interceptor)clazz.getDeclaredConstructor().newInstance();
            return interceptorInstance;
        }
        catch (Exception e)
        {
            logger.error("",e);
        }
        return null;
    }
}
